// strategyUtils.js - 存放策略相关的工具函数

/**
 * 生成实时MA信号
 * @param {Array} priceHistory - 价格历史
 * @param {Object} backtestSettings - 回测设置
 * @param {number} position - 当前仓位
 * @returns {Object|null} 信号对象或null
 */
export const generateRealTimeMASignal = (priceHistory, backtestSettings, position) => {
  const fastMA = backtestSettings.fastMAPeriod
  const slowMA = backtestSettings.slowMAPeriod
  
  if (priceHistory.length < slowMA) return null
  
  const prices = priceHistory.map(p => p.close)
  
  // 计算当前和上一个MA值
  const currentFastMA = prices.slice(-fastMA).reduce((a, b) => a + b, 0) / fastMA
  const currentSlowMA = prices.slice(-slowMA).reduce((a, b) => a + b, 0) / slowMA
  
  if (priceHistory.length < slowMA + 1) return null
  
  const prevFastMA = prices.slice(-(fastMA + 1), -1).reduce((a, b) => a + b, 0) / fastMA
  const prevSlowMA = prices.slice(-(slowMA + 1), -1).reduce((a, b) => a + b, 0) / slowMA
  
  // 金叉信号（买入）
  if (currentFastMA > currentSlowMA && prevFastMA <= prevSlowMA && position === 0) {
    return { type: 'buy', reason: 'MA金叉(实时)' }
  }
  
  // 死叉信号（卖出）
  if (currentFastMA < currentSlowMA && prevFastMA >= prevSlowMA && position > 0) {
    return { type: 'sell', reason: 'MA死叉(实时)' }
  }
  
  return null
}

/**
 * 生成实时RSI信号
 * @param {Array} priceHistory - 价格历史
 * @param {Object} backtestSettings - 回测设置
 * @param {number} position - 当前仓位
 * @returns {Object|null} 信号对象或null
 */
export const generateRealTimeRSISignal = (priceHistory, backtestSettings, position) => {
  const rsiPeriod = backtestSettings.rsiPeriod
  const overbought = backtestSettings.overbought
  const oversold = backtestSettings.oversold
  
  if (priceHistory.length < rsiPeriod + 1) return null
  
  // 计算RSI
  const prices = priceHistory.slice(-rsiPeriod - 1).map(p => p.close)
  let gains = 0, losses = 0
  
  for (let i = 1; i < prices.length; i++) {
    const change = prices[i] - prices[i - 1]
    if (change > 0) gains += change
    else losses += Math.abs(change)
  }
  
  const avgGain = gains / rsiPeriod
  const avgLoss = losses / rsiPeriod
  
  if (avgLoss === 0) return null
  
  const rs = avgGain / avgLoss
  const currentRSI = 100 - (100 / (1 + rs))
  
  // 计算前一个RSI
  const prevPrices = priceHistory.slice(-rsiPeriod - 2, -1).map(p => p.close)
  let prevGains = 0, prevLosses = 0
  
  for (let i = 1; i < prevPrices.length; i++) {
    const change = prevPrices[i] - prevPrices[i - 1]
    if (change > 0) prevGains += change
    else prevLosses += Math.abs(change)
  }
  
  const prevAvgGain = prevGains / rsiPeriod
  const prevAvgLoss = prevLosses / rsiPeriod
  const prevRS = prevAvgLoss === 0 ? 0 : prevAvgGain / prevAvgLoss
  const prevRSI = 100 - (100 / (1 + prevRS))
  
  // RSI从超卖区域上穿（买入）
  if (prevRSI <= oversold && currentRSI > oversold && position === 0) {
    return { type: 'buy', reason: `RSI超卖反弹(实时-${currentRSI.toFixed(1)})` }
  }
  
  // RSI从超买区域下穿（卖出）
  if (prevRSI >= overbought && currentRSI < overbought && position > 0) {
    return { type: 'sell', reason: `RSI超买回落(实时-${currentRSI.toFixed(1)})` }
  }
  
  return null
}

/**
 * 生成实时布林带信号
 * @param {Array} priceHistory - 价格历史
 * @param {Object} backtestSettings - 回测设置
 * @param {number} position - 当前仓位
 * @returns {Object|null} 信号对象或null
 */
export const generateRealTimeBollingerSignal = (priceHistory, backtestSettings, position) => {
  const bbPeriod = backtestSettings.bbPeriod
  const bbStdDev = backtestSettings.bbStdDev
  
  if (priceHistory.length < bbPeriod) return null
  
  const prices = priceHistory.slice(-bbPeriod).map(p => p.close)
  const middle = prices.reduce((a, b) => a + b, 0) / prices.length
  const stdDev = Math.sqrt(prices.map(x => Math.pow(x - middle, 2)).reduce((a, b) => a + b, 0) / prices.length)
  
  const upper = middle + (stdDev * bbStdDev)
  const lower = middle - (stdDev * bbStdDev)
  
  const currentPrice = priceHistory[priceHistory.length - 1].close
  
  // 价格触及下轨（买入）
  if (currentPrice <= lower && position === 0) {
    return { type: 'buy', reason: '价格触及布林带下轨(实时)' }
  }
  
  // 价格触及上轨（卖出）
  if (currentPrice >= upper && position > 0) {
    return { type: 'sell', reason: '价格触及布林带上轨(实时)' }
  }
  
  return null
}

/**
 * 生成实时自定义信号
 * @param {Array} priceHistory - 价格历史
 * @param {Object} backtestSettings - 回测设置
 * @param {number} position - 当前仓位
 * @returns {Object|null} 信号对象或null
 */
export const generateRealTimeCustomSignal = (priceHistory, backtestSettings, position) => {
  if (priceHistory.length < 5) return null
  
  const currentPrice = priceHistory[priceHistory.length - 1].close
  const recentPrices = priceHistory.slice(-5).map(p => p.close)
  const avgPrice = recentPrices.reduce((a, b) => a + b, 0) / 5
  
  // 价格突破平均线2%（买入）
  if (currentPrice > avgPrice * 1.02 && position === 0) {
    return { type: 'buy', reason: '价格突破(实时)' }
  }
  
  // 价格跌破平均线2%（卖出）
  if (currentPrice < avgPrice * 0.98 && position > 0) {
    return { type: 'sell', reason: '价格跌破止损(实时)' }
  }
  
  return null
}

/**
 * 生成实时VWAP信号
 * @param {Array} priceHistory - 价格历史
 * @param {number} position - 当前仓位
 * @returns {Object|null} 信号对象或null
 */
export const generateRealTimeVWAPSignal = (priceHistory, position) => {
  if (priceHistory.length < 20) return null
  
  // 简化的VWAP计算（实际应用中应该使用完整的VWAP计算）
  const recentData = priceHistory.slice(-20)
  const prices = recentData.map(p => p.close)
  const volumes = recentData.map(p => p.volume || 1) // 如果没有成交量数据，使用默认值1
  
  const vwap = prices.reduce((sum, price, i) => sum + price * volumes[i], 0) / volumes.reduce((a, b) => a + b, 0)
  const currentPrice = prices[prices.length - 1]
  
  // 简单的VWAP交叉策略
  if (currentPrice > vwap && position === 0) {
    return { type: 'buy', reason: '价格上穿VWAP(实时)' }
  } else if (currentPrice < vwap && position > 0) {
    return { type: 'sell', reason: '价格下穿VWAP(实时)' }
  }
  
  return null
}

/**
 * 生成实时ML策略1信号
 * @param {Array} priceHistory - 价格历史
 * @param {Object} backtestSettings - 回测设置
 * @param {number} position - 当前仓位
 * @param {Array} trades - 交易记录
 * @returns {Object|null} 信号对象或null
 */
export const generateRealTimeMLStrategy1Signal = (priceHistory, backtestSettings, position, trades) => {
  // 添加更全面的保护性检查
  if (!priceHistory || !Array.isArray(priceHistory) || priceHistory.length < 50) return null
  
  // 检查priceHistory中的元素是否包含所需的属性
  for (let i = 0; i < priceHistory.length; i++) {
    const item = priceHistory[i]
    if (!item || typeof item !== 'object' || !('close' in item)) {
      console.error('priceHistory contains invalid item at index', i, item)
      return null
    }
  }
  
  // 将价格历史转换为数据格式
  const data = priceHistory.map(p => ({
    date: p.date || new Date().toISOString().split('T')[0],
    close: typeof p.close === 'number' ? p.close : parseFloat(p.close) || 0,
    high: (typeof p.close === 'number' ? p.close : parseFloat(p.close) || 0) * 1.01, // 模拟高价
    low: (typeof p.close === 'number' ? p.close : parseFloat(p.close) || 0) * 0.99,  // 模拟低价
    volume: 1000 + Math.random() * 1000 // 模拟成交量
  }))
  
  const index = data.length - 1
  const features = calculateMLFeatures(data, index)
  
  if (!features) return null
  
  // 这里应该实现完整的ML策略逻辑
  // 为了简化，我们使用一个基础的动量策略作为示例
  
  const prices = data.map(d => d.close)
  const currentPrice = prices[prices.length - 1]
  
  // 计算简单动量指标
  const momentumPeriod = Math.min(10, prices.length)
  const momentum = (currentPrice - prices[prices.length - momentumPeriod - 1]) / prices[prices.length - momentumPeriod - 1]
  
  // 简单的动量策略
  if (momentum > 0.02 && position === 0) { // 2%以上的正动量
    return { type: 'buy', reason: `ML动量买入(实时-${(momentum * 100).toFixed(2)}%)` }
  } else if (momentum < -0.01 && position > 0) { // 1%以上的负动量
    return { type: 'sell', reason: `ML动量卖出(实时-${(momentum * 100).toFixed(2)}%)` }
  }
  
  // 检查止损止盈
  if (position > 0) {
    const lastBuyTrade = trades.filter(t => t.type === 'buy').pop()
    if (lastBuyTrade) {
      const stopLossPrice = lastBuyTrade.price * (1 - backtestSettings.stopLoss / 100)
      const takeProfitPrice = lastBuyTrade.price * (1 + backtestSettings.takeProfit / 100)
      
      if (currentPrice <= stopLossPrice) {
        return { type: 'sell', reason: `止损出局(价格: $${currentPrice.toFixed(2)})` }
      }
      
      if (currentPrice >= takeProfitPrice) {
        return { type: 'sell', reason: `止盈出局(价格: $${currentPrice.toFixed(2)})` }
      }
    }
  }
  
  return null
}